package com.you.atlas.web.place.module.screen;

import java.io.IOException;
import java.io.InputStream;

import org.apache.commons.fileupload.FileItem;
import org.springframework.beans.factory.annotation.Autowired;

import com.alibaba.china.fasttext.json.JSONObject;
import com.alibaba.citrus.service.uribroker.URIBrokerService;
import com.alibaba.citrus.service.uribroker.uri.GenericURIBroker;
import com.alibaba.citrus.turbine.TurbineRunData;
import com.you.common.file.ImageService;
import com.you.common.util.MixTool;

public class NotePhotoUpload {

    @Autowired
    private ImageService     imageService;

    @Autowired
    private URIBrokerService uriBrokerService;

    protected InputStream getInputStream(FileItem fileItem) {
        try {
            return fileItem.getInputStream();
        } catch (IOException e) {
            return null;
        }
    }

    public void execute(TurbineRunData rundata) throws IOException {

        JSONObject json = new JSONObject();
        FileItem fileItem = rundata.getParameters().getFileItem("Filedata");
        if (fileItem != null) {
            String imgUrl = imageService.scaleImg(getInputStream(fileItem), fileItem.getName(), 600, 450);
            String thumbImgUrl = imageService.scaleIcon(imgUrl, 96, 80);
            json.put("imgUrl", broke(imgUrl));
            json.put("thumbImgUrl", broke(thumbImgUrl));
            json.put("name", fileItem.getName());
            json.put("shortName", MixTool.shortFileName(fileItem.getName())+"...");
            rundata.getResponse().getWriter().write(json.toString());
        } else {
            json.put("error", "1");
            rundata.getResponse().getWriter().write(json.toString());

        }

    }

    private String broke(String imgUrl) {
        GenericURIBroker uriBroker = (GenericURIBroker) uriBrokerService.getURIBroker("uploadLink");
        return uriBroker.addPath(imgUrl).render();
    }
}
